#!/usr/bin/bash

DEFAULT_IMAGES_PATH="/etc/screen_inter_lock/default_images"

input=$1

if [ -f "$image_fg" ]; then
    image_fg=$input

elif [ -d "$image_fg"]; then
    image_fg=$(find "$input" -type f -name "*.png" 2>/dev/null | shuf -n 1)

fi


if [ -z $image_fg ]; then
    image_fg=$(find $DEFAULT_IMAGES_PATH -type f -name "*.png" 2>/dev/null | shuf -n 1)
fi

if [ -z $image_fg ]; then
    echo "Not input ImagePath"
    notify-send "ScreenInterLock" "Not input ImagePath" &>/dev/null
    exit 1
fi


if [ "$XDG_SESSION_TYPE" = "wayland" ]; then

    echo "Session Wayland depends: grim, imagemagick, swaylock"
    
    command -v grim 1>/dev/null
    if [ $? -ne 0 ]; then
        echo "Please install 'grim'"
        exit 1
    fi
    
    command -v swaylock 1>/dev/null
    if [ $? -ne 0 ]; then
        echo "Please install 'swaylock'"
        exit 1
    fi


    grim "$HOME/.cache/bg_image.tmp.png"
    
    convert "$HOME/.cache/bg_image.tmp.png" -blur 0x9 $image_fg -gravity center -composite "$HOME/.cache/bg_image.tmp.png"
    
    swaylock -i "$HOME/.cache/bg_image.tmp.png"

    rm "$HOME/.cache/bg_image.tmp.png"

else

    echo "Session X11 depends: scrot, imagemagick, i3lock"
    
    command -v scrot >/dev/null
    if [ $? -ne 0 ]; then
        echo "Please install 'scrot'"
        exit 1
    fi
    
    command -v i3lock >/dev/null
    if [ $? -ne 0 ]; then
        echo "Please install 'i3lock'"
        exit 1
    fi

    scrot "$HOME/.cache/bg_image.tmp.png"
    
    convert "$HOME/.cache/bg_image.tmp.png" -blur 0x9 $image_fg -gravity center -composite "$HOME/.cache/bg_image.tmp.png"
    
    i3lock -i "$HOME/.cache/bg_image.tmp.png"

    rm "$HOME/.cache/bg_image.tmp.png"
    
fi
